#!/usr/bin/python
# -*- coding: utf-8 -*-  # 编码声明，确保支持非 ASCII 字符

import json
import time
import common
import sys
try:
    # Python 2
    import urllib
    import urllib2
    import httplib
except ImportError:
    # Python 3
    import urllib.request as urllib_request
    import urllib.parse as urllib_parse
    import http.client as httplib



def send_post_request(url, data, max_retries=3):
    """ 发送 POST 请求 """
    json_data = json.dumps(data, ensure_ascii=False)
    headers = {'Content-Type': 'application/json'}
    retries = 0
    
    while retries < max_retries:
        # 发送 POST 请求
        if 'urllib2' in globals():
            req = urllib2.Request(url, json_data.encode('utf-8'), headers)
            response = urllib2.urlopen(req)
        else:
            req = urllib_request.Request(url, json_data.encode('utf-8'), headers)
            response = urllib_request.urlopen(req)
        
        # 获取响应状态码
        if response.getcode() == 200:
            content = response.read().decode('utf-8')  # 获取响应体内容并解码
            common.handle_response(content)  # 处理响应体
            break  # 如果状态码是 200，退出循环
        else:
            retries += 1
            print("请求失败，状态码: {}. 正在重试... ({}/{})".format(response.status, retries, max_retries))
            time.sleep(2)  # 等待 2 秒后重试



def main():
    # 初始化为1，表示失败
    result = 1
    
    # 从配置文件加载 URL 和 ID
    url, id_value = common.load_config()
    if not url or not id_value:
        print("配置文件加载失败，请检查配置文件")
        send_post_request(url, data={
            "id": id_value,
            "stat": result,
            "type": 1,
            "error": "https.yml配置文件加载失败"})
        sys.exit(1)
    
    # 检查命令行参数是否足够（现在只需要一个参数）
    if len(sys.argv) < 3:
        print("用法: /usr/sbin/migrear --recover_preset yes")
        send_post_request(url, data={
            "id": id_value,
            "stat": result,
            "type": 1,
            "error": "恢复命令中参数不足"})
        sys.exit(1)

    # 解析命令行参数
    args = sys.argv[1:]
    restore_args = {}
    try:
        for i in range(0, len(args), 2):
            if i + 1 >= len(args):
                raise ValueError("参数不完整: 缺少值")
            key = args[i]
            value = args[i + 1]
            if key.startswith("--"):
                restore_args[key] = value
            else:
                raise ValueError(f"未知参数: {key}")
    except ValueError as e:
        print(f"参数错误: {e}")
        sys.exit(1)

    # 构造恢复命令
    command = ["/usr/sbin/migrear", "--recover_preset", "yes"]

    if common.execute_script(command[0], command[1:]) == 0:
        print("恢复命令执行成功")
        result = 0
        send_post_request(url, {
            "id": id_value,
            "stat": result,
            "type": 3,
            "error": None})
    else:
        print("恢复命令执行失败")
        send_post_request(url, {
            "id": id_value,
            "stat": result,
            "type": 3,
            "error": "恢复失败"})
    
    common.execute_command("reboot")

if __name__ == '__main__':
    main()